﻿using HCQ2_Common;
using HCQ2_Common.Upload;
using HCQ2_Model;
using HCQ2_Model.DocModel;
using HCQ2_Model.DocModel.APIParam;
using HCQ2_Model.DocModel.APIResultModel;
using HCQ2_Model.DocModel.HeadModel;
using HCQ2_Model.SelectModel;
using HCQ2_Model.UploadModel;
using HCQ2_Model.ViewModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace HCQ2UI_Logic.DocumentController
{
    /// <summary>
    ///  头记英语 控制器
    /// </summary>
    public class HeadManagerController: BaseLogic
    {
        //**************************1.0 课件列表*****************************
        #region 1.0 默认首次进入课件列表 + ActionResult MakList()
        /// <summary>
        ///  默认首次进入课件列表
        /// </summary>
        /// <returns></returns>
        [HCQ2_Common.Attributes.Load]
        [HCQ2_Common.Attributes.Element]
        [HttpGet]
        public ActionResult MakList()
        {
            return View();
        }
        #endregion

        #region 1.1 初始化Table + ActionResult InitTable()
        /// <summary>
        ///  初始化Table
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InitTable(HeadTableParamModel model)
        {
            if (model.folder_id == 0)
                return null;
            int total = 0;
            List<DocTreeResultModel> list = operateContext.bllSession.T_DocumentInfo.GetTableData(model, out total);
            TableModel tModel = new TableModel()
            {
                total = total,
                rows = list
            };
            return Json(tModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        //**************************2.0 关卡列表*****************************
        #region 2.0 默认首次进入关卡列表 + ActionResult PassList()
        /// <summary>
        ///  默认首次进入关卡列表
        /// </summary>
        /// <returns></returns>
        [HCQ2_Common.Attributes.Load]
        [HCQ2_Common.Attributes.Element]
        [HttpGet]
        public ActionResult PassList()
        {
            return View();
        }
        #endregion

        #region 2.1 初始化Table + ActionResult InitPassTable(HeadTableParamModel model)
        /// <summary>
        ///  初始化Table
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InitPassTable(HeadTableParamModel model)
        {
            if (model.folder_id == 0)
                return null;
            int total = 0;
            List<HeadPassModel> list = operateContext.bllSession.T_VRCustomPass.GetTableData(model, out total);
            TableModel tModel = new TableModel()
            {
                total = total,
                rows = list
            };
            return Json(tModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 2.2 添加关卡 + ActionResult AddCustomPass(T_VRCustomPass model)
        /// <summary>
        ///  添加关卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddCustomPass(T_VRCustomPass model)
        {
            try
            {
                if(string.IsNullOrEmpty(model.file_name) || model.file_id<=0)
                    return operateContext.RedirectAjax(1, "请选择课件~", "", "");
                if (string.IsNullOrEmpty(model.cp_name))
                    return operateContext.RedirectAjax(1, "请填写关卡名称~", "", "");
                //判断关卡名称是否存在
                int markCount = operateContext.bllSession.T_VRCustomPass.SelectCount(s => s.file_id == model.file_id && s.cp_code.Equals(model.cp_code));
                if(markCount>0)
                    return operateContext.RedirectAjax(1, "当前关卡代码已在课件中存在~", "", "");
                model.create_name = operateContext.Usr.user_name;
                model.create_date = DateTime.Now;
                model.update_name= operateContext.Usr.user_name;
                model.update_date= DateTime.Now;
                int mark = operateContext.bllSession.T_VRCustomPass.Add(model);
                if (mark>0)
                    return operateContext.RedirectAjax(0, "关卡添加成功~", "", "");
                return operateContext.RedirectAjax(1, "关卡添加失败~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 2.3 编辑关卡 + ActionResult EditCustomPass(T_VRCustomPass model )
        /// <summary>
        ///  编辑关卡
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditCustomPass(T_VRCustomPass model)
        {
            try
            {
                if (string.IsNullOrEmpty(model.file_name) || model.file_id <= 0)
                    return operateContext.RedirectAjax(1, "请选择课件~", "", "");
                if (string.IsNullOrEmpty(model.cp_name))
                    return operateContext.RedirectAjax(1, "请填写关卡名称~", "", "");
                int markCount = operateContext.bllSession.T_VRCustomPass.SelectCount(s => s.file_id == model.file_id && s.cp_code.Equals(model.cp_code) && s.cp_id != model.cp_id);
                if (markCount > 0)
                    return operateContext.RedirectAjax(1, "当前关卡代码已在课件中存在，请重新设置~", "", "");
                model.update_name = operateContext.Usr.user_name;
                model.update_date = DateTime.Now;
                //编辑关卡课件
                int mark = operateContext.bllSession.T_VRCustomPass.Modify(model, s => s.cp_id == model.cp_id, "file_id", "file_name", "cp_name", "cp_code", "update_name", "update_date", "cp_note", "cp_order");
                if (mark > 0)
                    //修改单词所在课件
                    operateContext.bllSession.T_VRCustomPassWord.Modify(new T_VRCustomPassWord { file_id = model.file_id }, s => s.cp_id == model.cp_id, "file_id");
                return operateContext.RedirectAjax(0, "编辑关卡成功~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 2.4 删除关卡 +ActionResult DelCustomPass(int id)
        /// <summary>
        ///  删除关卡
        /// </summary>
        /// <param name="id">关卡id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DelCustomPass()
        {
            string cp_id = RequestHelper.GetStrByName("cp_id");
            if (string.IsNullOrEmpty(cp_id))
                return operateContext.RedirectAjax(1, "需要删除的数据不存在~", "", "");
            string[] ids = cp_id.Split(',');
            StringBuilder sb = new StringBuilder();
            foreach(var temp in ids)
            {
                int id = Helper.ToInt(temp);
                int mark = operateContext.bllSession.T_VRCustomPassWord.SelectCount(s => s.cp_id == id);
                if(mark<=0)
                    operateContext.bllSession.T_VRCustomPass.Delete(s => s.cp_id == id);
                else
                {
                    var query = operateContext.bllSession.T_VRCustomPass.Select(s => s.cp_id == id).FirstOrDefault();
                    sb.Append($"课件：【{query?.cp_name}】下存在单词，请先清理单词后再操作！");
                }
            }
            if(string.IsNullOrEmpty(sb.ToString()))
                return operateContext.RedirectAjax(0, "数据删除成功~", "", "");
            return operateContext.RedirectAjax(1, sb.ToString(), "", "");
        }
        #endregion

        #region 2.5 获取课件下拉 +ActionResult GetClassInfo(int id)
        /// <summary>
        ///  获取课件下拉
        /// </summary>
        /// <param name="id">目录id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetClassInfo(int id)
        {
            int fileStatus = RequestHelper.GetIntByName("fileStatus"),
                notStatus = RequestHelper.GetIntByName("notStatus");//是否排除审核未过的
            List<SelectModel> list = operateContext.bllSession.T_VRCustomPass.GetClassData(id, (fileStatus > 0 ? true : false), (notStatus > 0 ? true : false));
            return operateContext.RedirectAjax(0, "数据获取成功~", list, "");
        }
        #endregion

        #region 2.6 移动关卡 +ActionResult MovePass(MovePassParam param)
        /// <summary>
        ///  移动关卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult MovePass(MovePassParam param)
        {
            if (!ModelState.IsValid)
                return operateContext.RedirectAjax(1, getErrorMessage(ModelState), "", "");
            T_DocumentInfo info = operateContext.bllSession.T_DocumentInfo.Select(s => s.file_id == param.file_id).FirstOrDefault();
            if(info==null)
                return operateContext.RedirectAjax(1,"需要移入的课件异常！", "", "");
            //关卡
            T_VRCustomPass pass = new T_VRCustomPass { file_id = info.file_id, file_name = info.file_name };
            //单词
            T_VRCustomPassWord word = new T_VRCustomPassWord { file_id = info.file_id, file_name = info.file_name };
            //移动关卡、单词
            foreach (var cp_id in param.cp_id)
            {
                operateContext.bllSession.T_VRCustomPass.Modify(pass, s => s.cp_id == cp_id, "file_id", "file_name");
                operateContext.bllSession.T_VRCustomPassWord.Modify(word, s => s.cp_id == cp_id, "file_id", "file_name");
            }
            return operateContext.RedirectAjax(0, "数据移动成功~", "", "");
        }
        #endregion

        //**************************3.0 单词关卡列表*****************************
        #region 3.0 默认首次进入单词列表 + ActionResult WordList()
        /// <summary>
        ///  默认首次进入单词列表
        /// </summary>
        /// <returns></returns>
        [HCQ2_Common.Attributes.Load]
        [HCQ2_Common.Attributes.Element]
        [HttpGet]
        public ActionResult WordList()
        {
            return View();
        }
        #endregion

        #region 3.1 初始化Table + ActionResult InitWordTable(HeadTableParamModel model)
        /// <summary>
        ///  初始化Table
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InitWordTable(HeadWordParam model)
        {
            int total = 0;
            List<HeadWordModel> list = operateContext.bllSession.T_VRCustomPassWord.GetTableData(model, out total);
            TableModel tModel = new TableModel()
            {
                total = total,
                rows = list
            };
            return Json(tModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 3.2 获取关卡下拉 +ActionResult GetPassInfo(int id)
        /// <summary>
        ///  获取关卡下拉
        /// </summary>
        /// <param name="id">课件id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetPassInfo(int id)
        {
            if (id <= 0)
                return operateContext.RedirectAjax(1, "课件id异常~", "", "");
            List<SelectModel> list = operateContext.bllSession.T_VRCustomPassWord.GetPassData(id);
            return operateContext.RedirectAjax(0, "数据获取成功~", list, "");
        }
        #endregion

        #region 3.3 移动单词 +ActionResult MoveWord()
        /// <summary>
        ///  移动单词
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult MoveWord(MoveWordParam param)
        {
            if (!ModelState.IsValid)
                return operateContext.RedirectAjax(1, getErrorMessage(ModelState), "", "");
            T_VRCustomPassWord word = new T_VRCustomPassWord { cp_id = param.cp_id, cp_name = param.cp_name, file_id = param.file_id, file_name = param.file_name };
            foreach(var i in param.wp_id)
                operateContext.bllSession.T_VRCustomPassWord.Modify(word, s => s.pw_id == i, "cp_id", "cp_name", "file_id", "file_name");
            return operateContext.RedirectAjax(0, "数据移动成功~", "", "");
        }
        #endregion

        #region 3.4 添加关卡单词 + ActionResult AddWordPass(HeadWordModel model)
        /// <summary>
        ///  添加关卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddWordPass(HeadWordModel model)
        {
            try
            {
                ModelState.Remove("pw_id");
                if (!ModelState.IsValid)
                    return operateContext.RedirectAjax(1, getErrorMessage(ModelState), "", "");
                model.create_name = operateContext.Usr.user_name;
                model.update_name = operateContext.Usr.user_name;
                int markCount = operateContext.bllSession.T_VRCustomPassWord.Add(model.ToEntry());
                if (markCount > 0)
                    return operateContext.RedirectAjax(0, "单词添加成功~", "", "");
                return operateContext.RedirectAjax(1, "单词添加失败~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 3.5 编辑关卡单词 + ActionResult EditWordPass(HeadWordModel model )
        /// <summary>
        ///  编辑关卡单词
        /// </summary>
        /// <param name="model">单词对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditWordPass(HeadWordModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                    return operateContext.RedirectAjax(1, getErrorMessage(ModelState), "", "");
                model.update_name = operateContext.Usr.user_name;
                int markCount = operateContext.bllSession.T_VRCustomPassWord.Modify(model.ToEntry(),s=>s.pw_id==model.pw_id, "cp_id", "cp_name", "file_id", "file_name", "word", "gj_symbol", "kk_symbol", "cp_type", "china_mean", "update_name", "update_date", "cp_note");
                return operateContext.RedirectAjax(0, "单词更新成功~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 3.6 删除关卡单词 +ActionResult DelWordPass(int id)
        /// <summary>
        ///  删除关卡单词
        /// </summary>
        /// <param name="id">单词id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DelWordPass()
        {
            string ids = RequestHelper.GetStrByName("pwId");
            if(string.IsNullOrEmpty(ids))
                return operateContext.RedirectAjax(1, "需要删除的数据不存在~", "", "");
            string[] temp = ids.Split(',');
            foreach(string id in temp)
            {
                int pw_id = Convert.ToInt32(id);
                int mark = operateContext.bllSession.T_VRCustomPassWord.SelectCount(s => s.pw_id == pw_id);
                if (mark > 0)
                    operateContext.bllSession.T_VRCustomPassWord.Delete(s => s.pw_id == pw_id);
            }
            return operateContext.RedirectAjax(0, "数据删除成功~", "", "");
        }
        #endregion

        #region 3.7 导入关卡单词 +ActionResult ImportWordPass()
        /// <summary>
        ///  导入关卡单词
        /// </summary>
        /// <param name="id">单词id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ImportWordPass(HttpPostedFileBase excelFile)
        {
            try
            {
                int file_id = RequestHelper.GetIntByName("in_file_id");//课件id
                string file_name = RequestHelper.GetStrByName("in_file_name");//课件名称
                if(file_id<=0)
                    return operateContext.RedirectAjax(1, "请选择导入对应课件！", "", "");
                if(excelFile == null)
                    return operateContext.RedirectAjax(1, "请选择导入文件！", "", "");
                if (!Path.GetExtension(excelFile.FileName).Equals(".xlsx"))
                    return operateContext.RedirectAjax(1, "导入文件是.xlsx格式的excel文件！", "", "");
                //新的文件名
                string batchCode = Guid.NewGuid().ToString();
                #region 导入文件到临时目录
                string path = Server.MapPath("~/UpFile/ImportWord/temp/");
                if (!Directory.Exists(path.ToString()))
                    Directory.CreateDirectory(path.ToString());//文件夹不存在则创建
                string tempPath = Server.MapPath("~/UpFile/ImportWord/temp/") + batchCode + ".xlsx";
                excelFile.SaveAs(tempPath);
                #endregion
                Stopwatch sw1 = new Stopwatch();
                sw1.Start();
                List<string> mess = operateContext.bllSession.T_VRCustomPassWord.importWord(tempPath, file_id, file_name);
                sw1.Stop();
                if (mess.Count == 0)
                    return operateContext.RedirectAjax(0, string.Format("导入成功 用时：{0}秒。", Math.Round((double)sw1.ElapsedMilliseconds / 1000, 2)), "", "");
                return operateContext.RedirectAjax(1, "数据删除成功~", mess, "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion
        

        //**************************4.0 课件释意列表*************************
        #region 4.0 默认首次进入课件释意列表 + ActionResult MeanList()
        /// <summary>
        ///  默认首次进入课件释意列表
        /// </summary>
        /// <returns></returns>
        [HCQ2_Common.Attributes.Load]
        [HCQ2_Common.Attributes.Element]
        [HttpGet]
        public ActionResult MeanList()
        {
            return View();
        }
        #endregion

        #region 4.1 添加单词 + ActionResult AddWord(WordSenseModel model)
        /// <summary>
        ///  添加单词
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddWord(WordSenseModel model)
        {
            try
            {
                ModelState.Remove("ws_id");
                if (!ModelState.IsValid)
                    return operateContext.RedirectAjax(1, getErrorMessage(ModelState), "", "");
                model.create_name = operateContext.Usr.user_name;
                model.update_name = operateContext.Usr.user_name;
                int markCount = operateContext.bllSession.T_VRWordSense.Add(model.ToEntry());
                if (markCount > 0)
                    return operateContext.RedirectAjax(0, "单词添加成功~", "", "");
                return operateContext.RedirectAjax(1, "单词添加失败~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 4.2 编辑单词 + ActionResult EditWord(WordSenseModel model)
        /// <summary>
        ///  编辑单词
        /// </summary>
        /// <param name="model">单词对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditWord(WordSenseModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                    return operateContext.RedirectAjax(1, getErrorMessage(ModelState), "", "");
                model.update_name = operateContext.Usr.user_name;
                int markCount = operateContext.bllSession.T_VRWordSense.Modify(model.ToEntry(), s => s.ws_id == model.ws_id, "word", "gj_symbol", "kk_symbol", "cp_type", "china_mean", "ws_phrase", "example", "update_name", "update_date");
                return operateContext.RedirectAjax(0, "单词更新成功~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 4.3 删除单词 +ActionResult DelWordById(int id)
        /// <summary>
        ///  删除单词
        /// </summary>
        /// <param name="id">单词id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DelWordById()
        {
            string ids = RequestHelper.GetStrByName("ids");
            if(string.IsNullOrEmpty(ids))
                return operateContext.RedirectAjax(1, "需要删除的数据不存在~", "", "");
            string[] wsid = ids.Split(',');
            foreach (string id in wsid)
            {
                int ws_id = Helper.ToInt(id);
                operateContext.bllSession.T_VRWordSense.Delete(s => s.ws_id == ws_id);
            }
            return operateContext.RedirectAjax(0, "数据删除成功~", "", "");
        }
        #endregion

        #region 4.4 初始化单词释义Table + ActionResult InitWordSenseTable(WordSenseParam param)
        /// <summary>
        ///  初始化单词释义Table
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InitWordSenseTable(WordSenseParam param)
        {
            int total = 0;
            List<WordSenseModel> list = operateContext.bllSession.T_VRWordSense.GetSenseTableData(param, out total);
            TableModel tModel = new TableModel()
            {
                total = total,
                rows = list
            };
            return Json(tModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 4.5 导入单词 +ActionResult ImportWordSense(HttpPostedFileBase excelFile)
        /// <summary>
        ///  导入单词
        /// </summary>
        /// <param name="id">单词id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ImportWordSense(HttpPostedFileBase excelFile)
        {
            try
            {
                if (!Path.GetExtension(excelFile.FileName).Equals(".xlsx"))
                    return operateContext.RedirectAjax(1, "导入文件是.xlsx格式的excel文件！", "", "");
                //新的文件名
                string batchCode = Guid.NewGuid().ToString();
                #region 导入文件到临时目录
                string path = Server.MapPath("~/UpFile/ImportWord/temp/");
                if (!Directory.Exists(path.ToString()))
                    Directory.CreateDirectory(path.ToString());//文件夹不存在则创建
                string tempPath = Server.MapPath("~/UpFile/ImportWord/temp/") + batchCode + ".xlsx";
                excelFile.SaveAs(tempPath);
                #endregion
                Stopwatch sw1 = new Stopwatch();
                sw1.Start();
                List<string> mess = operateContext.bllSession.T_VRWordSense.importWord(tempPath);
                sw1.Stop();
                if (mess.Count == 0)
                    return operateContext.RedirectAjax(0, string.Format("导入成功 用时：{0}秒。", Math.Round((double)sw1.ElapsedMilliseconds / 1000, 2)), "", "");
                return operateContext.RedirectAjax(1, "数据删除成功~", mess, "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        //**************************5.0 单词检测记录*************************
        #region 5.0 默认首次进入单词检测记录 + ActionResult WordDetectionList()
        /// <summary>
        ///  默认首次进入单词检测记录
        /// </summary>
        /// <returns></returns>
        [HCQ2_Common.Attributes.Load]
        [HCQ2_Common.Attributes.Element]
        [HttpGet]
        public ActionResult WordDetectionList()
        {
            return View();
        }
        #endregion

        #region 5.1 初始化Table + ActionResult InitWordDetectionTable(WordDetectionParam param)
        /// <summary>
        ///  初始化Table
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InitWordDetectionTable(WordDetectionParam param)
        {
            int total = 0;
            List<WordDetectionResult> list = operateContext.bllSession.T_VRHeadWordMain.GetWordDetectionList(param, out total);
            TableModel tModel = new TableModel()
            {
                total = total,
                rows = list
            };
            return Json(tModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 5.2 删除单词检测记录 +ActionResult DelWordDetectionById(int id)
        /// <summary>
        ///  删除单词检测记录
        /// </summary>
        /// <param name="id">单词id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DelWordDetectionById()
        {
            string ids = RequestHelper.GetStrByName("ids");
            if (string.IsNullOrEmpty(ids))
                return operateContext.RedirectAjax(1, "需要删除的数据不存在~", "", "");
            List<int> list = new List<int>();
            try
            {
                string[] wdid = ids.Split(',');
                foreach (string wd in wdid)
                {
                    int id = Helper.ToInt(wd), 
                        w_id = operateContext.bllSession.T_VRHeadWordDetailed.Select(s => s.wd == id).FirstOrDefault().wh_id;
                    if(!list.Contains(w_id))
                        list.Add(w_id);//添加主表id
                    operateContext.bllSession.T_VRHeadWordDetailed.Delete(s => s.wd == id);
                }
                list.ForEach(s => {
                    int count = operateContext.bllSession.T_VRHeadWordDetailed.SelectCount(o => o.wh_id == s);
                    if (count <= 0)
                        operateContext.bllSession.T_VRHeadWordMain.Delete(o => o.wh_id == s);
                });
                return operateContext.RedirectAjax(0, "数据删除成功~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, "数据删除失败~", ex.Message, "");
            }
        }
        #endregion
    }
}
